package com.nh.orderAction;
import java.awt.print.PrinterJob;
import java.awt.print.Book;
import java.awt.print.Printable;
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.standard.PrinterName;

public class MyPrintTest
    implements Printable
{
  public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
      throws PrinterException
  {
    Graphics2D g2 = (Graphics2D) graphics;
    g2.setPaint(Color.black);
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    Font font = new Font("宋体", Font.BOLD, 10);
    g2.setFont(font);
    g2.drawString("afasdfad", 10, 10);
    font = new Font("黑体", Font.ITALIC, 18);
    g2.setFont(font);
    g2.drawString("第二行:", 10, 40);
    return Printable.PAGE_EXISTS;
  }

  public static void main(String[] args)
  {
    MyPrintTest myprinttest = new MyPrintTest();
    myprinttest.print();
  }

  public void print()
  {
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    Book book = new Book();
    book.append(new MyPrintTest(), printerJob.defaultPage());
    printerJob.setPageable(book);
    HashAttributeSet hs = new HashAttributeSet();
    String printerName="POS-80c";
    hs.add(new PrinterName(printerName,null));
    PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
    if(pss.length==0)
    {
      System.out.println("无法找到打印机:"+printerName);
      return ;
    }
    try
    {
      printerJob.setPrintService(pss[0]);
      printerJob.print();
    }
    catch (PrinterException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
}